package com.gobrs.async.core;

import com.gobrs.async.core.task.AsyncTask;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 任务接受者
 * 根据接受到的任务集，构建成任务流：TaskFlow.denpendedTasks
 */
public class TaskReceive {

    /**
     * 任务流
     */
    private final TaskFlow taskFlow;

    /**
     * 缓存当前处理后的任务节点，之后根据当前缓存的任务节点添加子任务节点
     */
    private List<AsyncTask> cacheTaskList;

    TaskReceive(TaskFlow taskFlow, List<AsyncTask> taskList) {
        synchronized (taskFlow) {
            this.taskFlow = taskFlow;
            this.cacheTaskList = new ArrayList<>(taskList.size());
            /**
             *  src -> dest
             */
            copyList(taskList, this.cacheTaskList);
            for (AsyncTask task : taskList) {
                taskFlow.addDependency(task, null);
            }
        }
    }

    /**
     * 给 this.cacheTaskList 添加子任务节点
     */
    public TaskReceive then(boolean clear, AsyncTask... asyncTasks) {
        synchronized (taskFlow) {
            for (AsyncTask from : this.cacheTaskList) {
                for (AsyncTask to : asyncTasks) {
                    taskFlow.addDependency(from, to);
                }
            }
            for (AsyncTask to : asyncTasks) {
                taskFlow.addDependency(to, null);
            }
            /**
             *  for Compatible with regular commas so note
             */
            if (clear) {
                this.cacheTaskList = new ArrayList<>(asyncTasks.length);
                copyList(Arrays.asList(asyncTasks), this.cacheTaskList);
            }
            return this;
        }
    }

    public void refresh(List<AsyncTask> cacheTaskList) {
        this.cacheTaskList.clear();
        this.cacheTaskList.addAll(cacheTaskList);
    }

    private void copyList(List<AsyncTask> src, List<AsyncTask> dest) {
        dest.addAll(src);
    }

}
